import uvicorn
import psutil
import os
import signal
from pathlib import Path

def kill_process_on_port(port):
    """杀死占用指定端口的进程"""
    try:
        for conn in psutil.net_connections():
            if conn.laddr.port == port and conn.status == 'LISTEN':
                try:
                    os.kill(conn.pid, signal.SIGTERM)
                    print(f"已终止占用端口 {port} 的进程 (PID: {conn.pid})")
                    return True
                except ProcessLookupError:
                    pass
    except (psutil.AccessDenied, psutil.NoSuchProcess):
        pass
    return False

def main():
    # 创建日志目录
    log_dir = Path("logs")
    log_dir.mkdir(exist_ok=True)
    
    # 设置端口
    port = 8000
    
    # 如果端口被占用，先杀死占用进程
    kill_process_on_port(port)
    
    # 启动服务
    uvicorn.run(
        "app.main:app",
        host="127.0.0.1",
        port=port,
        reload=True,
        reload_dirs=["app"]
    )

if __name__ == "__main__":
    main() 